//
//  DatabaseManagement.m
//  sqlite
//
//  Created by 谢泽锋 on 2017/10/13.
//  Copyright © 2017年 Xie泽锋. All rights reserved.
//

#import "DatabaseManagement.h"
#import "MessageModel.h"
@implementation DatabaseManagement
static DatabaseManagement * dataBase;
+(instancetype)CreateDatabase:(NSString*)DatabaseName{
    if (!dataBase) {
        
    
        dataBase = [[DatabaseManagement alloc]init];
    
        
    }
    //1.获得数据库文件的路径
    NSString *doc=[NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) lastObject];
    NSString * sqliteName = [NSString stringWithFormat:@"%@.sqlite",DatabaseName];
    NSString *fileName=[doc stringByAppendingPathComponent:sqliteName];
    // .获得数据库
    FMDatabase *db=[FMDatabase databaseWithPath:fileName];
    
    // .打开数据库
    if ([db open]) {
        // .创表
        //name 用户名
        //type 消息类型（发送者）
        //messageType 消息类型（语音 或者文字）
        //MessageContent 消息内容
        //time 发送时间
        //chatType 聊天类型 （单聊，群聊）
        
      BOOL result=[db executeUpdate:@"CREATE TABLE IF NOT EXISTS t_student (id integer PRIMARY KEY AUTOINCREMENT, name text NOT NULL, chatType integer NOT NULL,time integer,messageType integer,messageContent text NOT NULL,sendObject integer NOT NULL,ConversationID text NOT NULL,UserAccount text NOT NULL);"];
        if (result)
        {
            NSLog(@"创表成功");
        }else{
            NSLog(@"创表失败");
        }
    }
    dataBase.db=db;
    return dataBase;
}
-(void)insertData:(MessageModel*)message
{
        // executeUpdate : 不确定的参数用?来占位
        [self.db executeUpdate:@"INSERT INTO t_student (name, chatType,time,messageType,messageContent,sendObject,ConversationID,UserAccount) VALUES (?, ?, ?, ?, ?, ?, ?, ?);", message.name, @(message.chatType),@(message.time),@(message.messageType),message.messageContent,@(message.sendObject),message.ConversationID,message.UserAccount];
}


-(NSArray*)queryData:(long  int)startTime Page:(int)page ConversationID:(NSString * )ConversationID
{
//       NSString * query =  [NSString stringWithFormat:@"select * from t_student where time < '%ld' and ConversationID = '%@'  order by id desc limit 100 offset 2 ", startTime,ConversationID];

//    NSString * query =  [NSString stringWithFormat:@"select * from t_student where time < '%ld' and ConversationID = '%@'  order by id desc limit 15 offset '%d'", startTime,ConversationID,page*15];
    NSString * query =  [NSString stringWithFormat:@"select * from t_student where time < '%ld' and ConversationID = '%@'  order by id desc limit 15 offset '%d'", startTime,ConversationID,page*15];

    
//    NSString * query =  [NSString stringWithFormat:@"select * from t_student   order by id desc limit 20 offset '%d' ",page*20];

    //每页20条数据
//    NSString * query =  [NSString stringWithFormat:@"select * from t_student where time < '%lld' and UserAccount = '%%%@%%'  order by id desc limit 20 offset '%d' ", startTime,ConversationID,page*20];
    FMResultSet *rs = [self.db executeQuery:query];
    NSMutableArray * alldata = [NSMutableArray array];
    while ([rs next]) {
        MessageModel * model = [MessageModel new];
        model.messageContent = [rs stringForColumn:@"messageContent"];
        model.name = [rs stringForColumn:@"name"];
        model.chatType = [[rs stringForColumn:@"chatType"] intValue];
        model.messageType = [[rs stringForColumn:@"messageType"] intValue];
        model.ConversationID = [rs stringForColumn:@"ConversationID"];
        model.UserAccount = [rs stringForColumn:@"UserAccount"];
        model.sendObject = [[rs stringForColumn:@"sendObject"] intValue];
        model.time = [[rs stringForColumn:@"time"] intValue];
        [alldata addObject:model];
        NSLog(@"%@  name ==  %@",[rs stringForColumn:@"time"],[rs stringForColumn:@"name"]);
    }
  
    return   [[alldata reverseObjectEnumerator] allObjects];
}



@end
